<?php

namespace App\AdminModule\Presenters;

use \Nette\Application\UI\Form,
    App\Model\Dao\Article,
    App\Model\Dao\Photo,
    \App\Component\PhotoList,
    \Grido, 
    \Grido\Grid, 
    \Grido\Components\Columns,
    \Grido\DataSources\Doctrine;

/**
 * Article presenter.
 */
class ArticlePresenter extends BasePresenter {
 
  /** @var \Kdyby\Doctrine\EntityManager @inject */
  public $em;
  
  /** @var \App\Model\UserManager @inject */
  public $um;
  
  private $article;
  
  /**
   * Add article action
   * @param int $id
   * @return boolean
   */
  public function actionAdd($id){
    if(!isset($id)){
      return;
    }
    
    $article = $this->em->getDao(Article::getClassName())->find($id);
    
    if($article){
      if($this->user->isInRole('admin') || $article->getUser()->getId() == $this->user->getId()){
        $this->article = $article;
      }
    }
  }
  
  /**
   * Add article form
   * @param String $name
   * @return \Nette\Application\UI\Form
   */
  public function createComponentAddArticleForm($name){
    $form = new Form();
    $form->addText('title', 'Titulek')->addRule(Form::FILLED, 'Titulek musí být vyplněn');
    $form->addText('link', 'Link')->addRule(Form::FILLED, 'Link musí být vyplněn');
    $form->addText('description', 'Popis')->addRule(Form::FILLED, 'Popis musí být vyplněn');
    $form->addText('keywords', 'Klíčová slova')->addRule(Form::FILLED, 'Klíčová slova musí být vyplněna');
    $form->addTextArea('content', 'Obsah')->addRule(Form::FILLED, 'Titulek musí být vyplněn');

    if($this->article){
      $form['title']->setDefaultValue($this->article->getTitle());
      $form['link']->setDefaultValue($this->article->getLink());
      $form['description']->setDefaultValue($this->article->getDescription());
      $form['keywords']->setDefaultValue($this->article->getKeywords());
      $form['content']->setDefaultValue($this->article->getContent());
    }
    
    $form->addSubmit('send');
    $form->onSuccess[] = callback($this, 'addArticleFormSuccess');
    
    return $form;
  }
  
  /**
   * Handle for delete article
   * @param int $id
   */
  public function handleDelete($id){
    if(!$this->user->isInRole('admin')){
      $this->redirect('Homepage:default');
    }
    
    $article = $this->em->getDao(Article::getClassName())->find($id);
    
    if($article){
      $this->em->remove($article);
      $this->em->flush();
    }
    
    $this->redirect('Article:default');
  }
  
   public function handleActivate($id){
    if(!$this->user->isInRole('admin')){
      $this->redirect('Homepage:default');
    }
    
    $article = $this->em->getDao(Article::getClassName())->find($id);
    
    if($article){
      $article->setActive(1);
      $this->em->flush();
    }
    
    $this->redirect('Article:default');
  }
  
     public function handleDeactivate($id){
    if(!$this->user->isInRole('admin')){
      $this->redirect('Homepage:default');
    }
    
    $article = $this->em->getDao(Article::getClassName())->find($id);
    
    if($article){
      $article->setActive(0);
      $this->em->flush();
    }
    
    $this->redirect('Article:default');
  }
  
  /**
   * Create component Article grid
   * @param String $name
   * @return \Grido\Grid
   */
  public function createComponentArticleGrid($name){
    if($this->user->isInRole('admin')){
      $qb = $this->em->createQueryBuilder()
        ->addSelect('a.id AS id')
        ->addSelect('a.title AS title')
        ->addSelect('a.link AS link')
        ->addSelect('a.active AS active')
        ->addSelect('a.created AS created')
        ->addSelect('u.login AS author')
        ->from(Article::getClassName(), ' a')
        ->innerJoin('a.user', 'u');
    
      $articles =  $qb->getQuery()->getArrayResult();
      
    }else if($this->user->isInRole('writer')){
      $qb = $this->em->createQueryBuilder()
        ->addSelect('a.id AS id')
        ->addSelect('a.title AS title')
        ->addSelect('a.active AS active')
        ->addSelect('a.link AS link')
        ->addSelect('a.created AS created')
        ->addSelect('u.login AS author')
        ->from(Article::getClassName(), ' a')
        ->innerJoin('a.user', 'u')
        ->where('u.id = ' . $this->user->getId());
      $articles =  $qb->getQuery()->getArrayResult();
    }

    $g = new Grid($this, $name);

    // Grido data
    $g->model = $articles;
    
    $g->addColumnText('id', 'ID')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('title', 'Titulek')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('link', 'Link')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('author', 'Autor')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('active', 'Aktivní')
        ->setSortable()
        ->setFilterText();
    
    $g->addColumnText('created', 'Vytvořeno')
        ->setSortable()
        ->setFilterText();
    
    $g->getColumn('created')->setCustomRender(function($item){
        return $item['created']->format('d.m.Y');
      });
    
    // Create edit button
    $g->addActionHref('edit', 'Edit', 'Article:add');
    $g->getAction('edit')->setIcon('pencil')->setPrimaryKey('id');
    
    // Create edit button
    if($this->user->isInRole('admin')){
      $g->addActionHref('activate', 'Aktivovat', 'activate!')
        ->setIcon('pencil')->setPrimaryKey('id');
      
      $g->addActionHref('deactivate', 'Deaktivovat', 'deactivate!')
        ->setIcon('pencil')->setPrimaryKey('id');
   
      $g->addActionHref('delete', 'Smazat', 'delete!')
        ->setIcon('remove')->setPrimaryKey('id');
    }
    
    // Return grido
    $g->filterRenderType = Grido\Components\Filters\Filter::RENDER_INNER;
    $g->setExport();
    return $g;
  }
  
  /**
   * Executing article form
   * @param type $form
   */
  public function addArticleFormSuccess($form){
    $values = $form->getValues();
    $user = $this->um->getUserById($this->user->getId());

    if(isset($this->article)){
      $this->article->setUser($user);
      $this->article->setTitle($values['title']);
      $this->article->setLink($values['link']);
      $this->article->setDescription($values['description']);
      $this->article->setKeywords($values['keywords']);
      $this->article->setContent($values['content']);
      $this->article->setActive(0);
      $this->em->persist($this->article);
    }else{
      $article = new Article();
      $article->setUser($user);
      $article->setTitle($values['title']);
      $article->setLink($values['link']);
      $article->setDescription($values['description']);
      $article->setKeywords($values['keywords']);
      $article->setContent($values['content']);
      $article->setCreated(new \DateTime());
      $article->setActive(0);
      $this->em->persist($article);
    }

    $this->em->flush();

    $this->flashMessage('Článek byl uložen', 'success');
    $this->redirect('Article:default');
  }
  
  /**
   * Photos component
   * @param String $name
   * @return PhotoList
   */
  public function createComponentPhotoList($name){
    $photoList = new PhotoList();
    return $photoList->init($this->em->getDao(Photo::getClassName())->findBy(array(), array('id' => 'desc')));
  }
}
